package com.xxxx.yoyo.adminweb;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xxxx.yoyo.bean.Type;
import com.xxxx.yoyo.service.ITypeService;
import com.xxxx.yoyo.service.impl.TypeServiceImpl;


@WebServlet("/admin/typeEdit")
public class TypeEditServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ITypeService typeService = new TypeServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获取前端页面传递过来的参数id
		String typeIdstr = request.getParameter("id");
		int typeId = Integer.parseInt (typeIdstr);
		
		//根据宠物分类的id获取宠物分类
		Type type = typeService.getTypeById(typeId);
		//把type存入cequest中，供/admin/type_edit.jsp使用
		request.setAttribute("type", type);
		
		//设置导航条上的[宠物大类管理]处于选中状态
		request.setAttribute("flag",4);
		
		//请求转发，跳转到/admin/type_edit.jsp文件
		request.getRequestDispatcher ("/admin/type_edit.jsp").forward(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码格式为UTF-8,解决请求参数中文乱码
		request.setCharacterEncoding ("UTF-8");
		
		//获取前端页面传递过来的参数id,name
		String typeIdstr = request.getParameter("id");
		int typeId = Integer.parseInt(typeIdstr);
		String name = request.getParameter("name");
		
		//根据宠物分类的id获取宠物分类
		Type type = typeService.getTypeById(typeId);
		//修改type的name
		type.setName(name);
		
		//更新宠物分类的信息（更新数据库）
		boolean isSuccess = typeService.updateType(type);
		if(isSuccess){
			//提示成功信息
			request.setAttribute("msg","宠物大类的信息修改成功！");
		}else {
			//提示错误信息
			request.setAttribute("msg","修改失败！宠物大类的名称不能超过20个字！");
		}
		
		//设置导航条上的[宠物大类管理]处于选中状态
		request.setAttribute("flag",4);
		
		//根据宠物分类的id获取宠物分类
		Type findedType = typeService.getTypeById(typeId);
		//把findedType存入request中，供/admin/type edit.jsp使用
		request.setAttribute("type", findedType);
		
		//请求转发，跳转到/admin/type_edit.jsp页面
		request.getRequestDispatcher ("/admin/type_edit.jsp").forward(request, response);
	}

}
